<template>
    <el-card style="height: 76px;">
        <el-form :inline="true" class="topForm">
            <el-form-item label="职位搜索">
                <el-input placeholder="请输入搜索的职位名称" v-model="keywords"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" size="default" :disabled="keywords ? false : true" @click=search>搜索</el-button>
                <el-button type="primary" size="default" @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>
    <el-card style="margin:10px 0">
        <el-button type="primary" size="default" icon="Plus" @click="addRole">{{ RoleParams.id ? '更新职位' : '添加职位'
        }}</el-button>
        <el-table border style="margin: 10px 0;" :data="allRole">
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column label="职位ID" align="center" prop="id"></el-table-column>
            <el-table-column label="职位名称" show-overflow-tooltip prop="roleName" align="center"></el-table-column>
            <el-table-column label="创建时间" show-overflow-tooltip prop="createTime" align="center"></el-table-column>
            <el-table-column label="更新时间" show-overflow-tooltip prop="updateTime" align="center"></el-table-column>
            <el-table-column label="操作" algin="center" width="300px" align="center">
                <!-- row 代表一个职位对象 -->
                <template #="{ row, $idnex }">
                    <el-button type="primary" size="small" icon="User" @click="setPermission(row)">分配职权</el-button>
                    <el-button type="primary" size="small" icon="Edit" @click="editRole(row)">编辑</el-button>
                    <el-popconfirm :title="`确定要删除${row.roleName}吗?`" width="200px" @confirm="removeRole(row)">
                        <template #reference>
                            <el-button type="primary" size="small" icon="Delete">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[3, 5, 7, 10]"
            :background="true" layout="prev, pager, next, jumper,->, sizes,total" :total="total"
            @current-change="getHasRole" @size-change="sizeChange" />
    </el-card>
    <!-- 添加|更新 职位的对话框 -->
    <el-dialog v-model="dialog" title="添加职位">
        <el-form :model="RoleParams" :rules="rules" ref="roleForm">
            <el-form-item label="职位名称" prop="roleName">
                <el-input placeholder="请输入职位名称" v-model="RoleParams.roleName"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button type="primary" size="default" @click="dialog = false">取消</el-button>
            <el-button type="primary" size="default" @click="save">确定</el-button>
        </template>
    </el-dialog>
    <!-- 抽屉组件:分配用户的菜单权限 -->
    <el-drawer v-model="drawer">
        <template #header>
            <h4>分配权限</h4>
        </template>
        <template #default>
            <el-tree ref="tree" :data="menuArr" show-checkbox node-key="id" default-expanded-all
                :default-checked-keys="idArr" :props="defaultProps" />
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="drawer = false">取消</el-button>
                <el-button type="primary" @click="handler">确认</el-button>
            </div>
        </template>
    </el-drawer>
</template>
<script setup lang='ts'>
import { ref, onMounted, reactive, nextTick } from 'vue'
// 引入请求全部角色数据的函数 
import { reqAllRole, reqAddOrUpdata, reqSetPermission, reqRemoveRole, reqAllPermission } from '@/api/acl/role'
// 引入数据的类型
import type { Records, MenuList, AllRoleResponseData, RoleData, MenuResponseData } from '@/api/acl/role/type';
// 引入导航骨架的仓库
import useLayoutSettingStore from '@/store/modules/setting';
import { ElMessage } from 'element-plus';
// 实例化骨架仓库
let settignStore = useLayoutSettingStore()
// 当前的页码
let pageNo = ref<number>(0)
// 单页数据
let pageSize = ref<number>(3)
// 数据总数
let total = ref<number>(0)
// 搜索的关键字
let keywords = ref<string>('')
// 定义全部职位的数据的数组
let allRole = ref<Records>([])
// 控制更新|添加 对话框的显示与隐藏
let dialog = ref<boolean>(false)
// 收集新增职位数据
let RoleParams = reactive<RoleData>({
    roleName: ''
})
// 控制分配权限显隐的变量
let drawer = ref<boolean>(false)
// 获取form组件
let roleForm = ref()
// 存储职位信息接口返回的数据
let menuArr = ref<MenuList>([])
// 存储勾选的ID的数组
let idArr = ref<number[]>([])


// 定义获取全部角色的函数
const getHasRole = async (paper = 1) => {
    // 修改当前页码
    pageNo.value = paper
    let result: AllRoleResponseData = await reqAllRole(pageNo.value, pageSize.value, keywords.value)
    if (result.code == 200) {
        allRole.value = result.data.records;
        total.value = result.data.total;
    }
}
//下拉菜单变化的回调
const sizeChange = () => {
    getHasRole()
}
// 搜索按钮的回调
const search = () => {
    // 发起请求
    getHasRole()
    // 重置关键字
    keywords.value = ''
}
// 组件挂载时获取数据
onMounted(() => {
    getHasRole()
});
// 获取tree控件的实例
let tree = ref()
// 重置按钮的回调
const reset = () => {
    settignStore.refresh = !settignStore.refresh;
}
//添加职位的按钮
const addRole = () => {
    // 显示对话框
    dialog.value = true;
    // 清空数组的数据
    Object.assign(RoleParams, {
        roleName: '',
        id: 0
    })
    // 清空上一次表单校验错误的结果
    nextTick(() => {
        roleForm.value.clearValidate('roleName');
    })
}
//更新职位的按钮
const editRole = (row: RoleData) => {
    // 显示对话框
    dialog.value = true;
    // 存储已有的职位
    Object.assign(RoleParams, row);
    // 清空上一次表单校验错误的结果
    nextTick(() => {
        roleForm.value.clearValidate('roleName');
    })
}
// 校验职位名称的方法
const validatorRoleName = (rule: any, value: any, callBack: any) => {
    if (value.trim().length >= 2) {
        callBack();
    } else {
        callBack(new Error('职位名称至少两位'))
    }
}

// 添加职位的校验规则
const rules = {
    roleName: [
        { required: true, trigger: 'blur', validator: validatorRoleName }
    ]
}
// 添加职位的确认按钮的回调函数
const save = async () => {
    await roleForm.value.validate();
    // 添加|更新职位
    let result: any = await reqAddOrUpdata(RoleParams)
    console.log(result)
    if (result.code == 200) {
        ElMessage({ type: 'success', message: RoleParams.id ? '更新成功' : '添加成功' })
        getHasRole(RoleParams.id ? pageNo.value : 1);
    } else {
        ElMessage({ type: 'error', message: RoleParams.id ? '更新失败' : '添加失败' })
    }
    dialog.value = false;
}
// 分配权限按钮的回调
const setPermission = async (row: RoleData) => {
    // 显示抽屉
    drawer.value = true;
    //收集当前要分类权限的职位的数据
    Object.assign(RoleParams, row);
    let result: MenuResponseData = await reqAllPermission(row.id as number)
    if (result.code == 200) {
        menuArr.value = result.data;
        idArr.value = filterSelect(menuArr.value, []);
    }
}
// 递归判断数据的函数
const filterSelect = (allData: any, initArr: any) => {
    allData.forEach((item: any) => {
        if (item.select && item.level == 4) {
            initArr.push(item.id)
        }
        if (item.children && item.children.length > 0) {
            filterSelect(item.children, initArr)
        }
    })
    return initArr
}
// 树形控件的数据
const defaultProps = {
    children: 'children',
    label: 'name',
}

// 分配权限的抽屉的确认按钮的回调
const handler = async () => {
    // 职位的ID
    let roleId = (RoleParams.id as number);
    // 选中节点的ID
    let arr = tree.value.getCheckedKeys();
    // 半选的ID
    let arr1 = tree.value.getHalfCheckedKeys();
    let permissionId = arr.concat(arr1);
    // 发起下发权限的请求
    let result: any = await reqSetPermission(roleId, permissionId)
    if (result.code == 200) {
        ElMessage({ type: 'success', message: '分配职位成功' })
        // 关闭抽屉
        drawer.value = false;
        // 页面刷新
        window.location.reload()
    } else {
        ElMessage({ type: 'error', message: '分配职位失败' })
        // 关闭抽屉
        drawer.value = false;
    }
}
// 删除已有的职位的方法
const removeRole = async (row: RoleData) => {
    let result: any = await reqRemoveRole(row.id as number)
    if (result.code == 200) {
        ElMessage({ type: "success", message: '删除成功' })
        getHasRole(allRole.value.length > 1 ? pageNo.value : pageNo.value - 1)
    } else {
        ElMessage({ type: "error", message: '删除失败' })
    }
}
</script>
<style lang='scss' scoped>
.topForm {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
</style>